import json
from urllib.request import urlopen

import coin2.support.product_info.spot_binance_v1 as binance_pi
import coin2.support.product_info.spot_okex_v3 as okex_pi
import coin2.support.product_info.spot_huobi_v1 as huobi_pi
import coin2.support.product_info.spot_bithumb_v2 as bithumb_pi
import coin2.support.product_info.spot_coinone_v2 as coinone_pi
import coin2.support.product_info.spot_upbit_v1 as upbit_pi

binance_pi_data = binance_pi.generate()
huobi_pi_data = huobi_pi.generate()
okex_pi_data = okex_pi.generate()
bithumb_pi_data = bithumb_pi.generate()
coinone_pi_data = coinone_pi.generate()
upbit_pi_data = upbit_pi.generate()


def get_24_hour_amount(symbol):
  url = 'https://api.binance.com/api/v3/ticker/24hr?symbol=' + symbol
  print(url)
  raw = urlopen(url, timeout=15).read()
  data = json.loads(raw)
  if 'quoteVolume' in data:
    return float(data['quoteVolume'])
  else:
    return 0

def get_24_hour_amount2(symbol):
  url = 'https://api.bithumb.com/public/ticker/' + symbol
  print(url)
  raw = urlopen(url, timeout=15).read()
  data = json.loads(raw)
  if 'acc_trade_value_24H' in data['data']:
    return float(data['data']['acc_trade_value_24H'])
  else:
    return 0


def find_match_pairs(pi_data_0, pi_data_1):
  match_pairs = []
  for info1 in pi_data_0:
    for info2 in pi_data_1:
      if info1['base'] == info2['base']:
        if info1['quote'] == 'USDT':
          info1['quoteVolume'] = get_24_hour_amount(info1['symbol'].replace('-', ''))
          info2['quoteVolume'] = get_24_hour_amount2(info2['symbol'].replace('-', '_'))
        match_pairs.append((info1, info2))
  return match_pairs


info_list = find_match_pairs(binance_pi_data, coinone_pi_data)
x = [info for info in info_list if 'USDT' in info[0]['symbol']]
x.sort(key=lambda x:x[1]['quoteVolume'])
print(json.dumps(x, indent=2))
